package com.example.com.android.bubble;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnKeyListener;

import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageSwitcher;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	EditText editText1, editText2;
	TextView textView1,TextView01;
	Button button1, button2,button3, button4, button5;
	int[] input_data = new int[12];
	String myInputValue;
	int inputInt =0;
	final Context context = this;
	//new char initialize
	String newChar = "";
	int inputCounter = 0;
	int inputElementCount = 12;
	int inputMinElementCount = 10;
	int inputMsxElementCount = 12;
	int inputStartRange = 1;
	int inputEndRange = 100;
	boolean isConfigchange = false;
    int inputMinCount = 0;
    int inputMaxCount = 0;
  	int inputStart = 0;
  	int inputEnd = 0;
  	Toast toastMsg;
  	boolean isduplicate =false;
  	boolean isinValid =false;
  	private ImageSwitcher imageSwitcher;
  	int position=0;
  	
		
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		editText1 = (EditText)findViewById(R.id.editText1);
		editText2 = (EditText)findViewById(R.id.editText2);
		button1 = (Button)findViewById(R.id.button1);
		button2 = (Button)findViewById(R.id.button2);
		button3 = (Button)findViewById(R.id.button3);
		button4 = (Button)findViewById(R.id.button4);
		button5 = (Button)findViewById(R.id.button5);
		textView1 = (TextView)findViewById(R.id.textView1);
		TextView01 = (TextView)findViewById(R.id.TextView01);
		
		
		editText1.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {	
				char currentChar=0;
				//read last character
				if(isduplicate == true || isinValid ==true){
					isduplicate = false;
					isinValid=false;
					position = editText1.getText().length();
				}
				else
					position=start;
				
				 try{
					 	currentChar = s.charAt(position);
	                	
				
				//conver to string
				String _currentChar = Character.toString(currentChar);				
				if(_currentChar.equals(",")){					
					//validate
					if(!newChar.isEmpty()){
						
					int currentNumber = Integer.parseInt(newChar);
						if(currentNumber ==0){
							finish();
			                System.exit(0);
						}
						//check if its between 0 and 100
						if(currentNumber>inputStartRange && currentNumber<inputEndRange){
							//check for duplicate							
							for(int i = 0; i<input_data.length; i++){
								if(currentNumber == input_data[i])
								{
									
									final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					        				context);
					        			// set title
					        			alertDialogBuilder.setTitle("Error: ");
					        			newChar ="";
					        			isduplicate = true;
					        			alertDialogBuilder.setCancelable(false);
					        			Toast.makeText(getApplicationContext(), "(1)is a comma valid"+newChar, Toast.LENGTH_LONG).show();
					        			alertDialogBuilder.setMessage("Entered duplicate Number: Please enter another number!");					        			        			
					        			alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					        				public void onClick(DialogInterface dialog, int whichButton) {
					        					return;
					        				  }
					        				});
					        				// show it
					        			alertDialogBuilder.show();
					        			

								}
								
							}
							if(isduplicate == false)
							{
								input_data[inputCounter] = Integer.parseInt(newChar);
								//Toast.makeText(getApplicationContext(), "(2)is a comma valid"+newChar, Toast.LENGTH_LONG).show();
								newChar = "";
								inputCounter++;
								//editText2.setText(Integer.toString(inputCounter));
								TextView01.setText("Total Number Entered: "+inputCounter + "Remaining Max Entries"+(inputMsxElementCount-inputCounter));
								
								if(inputCounter >=inputMinElementCount || inputCounter >= inputElementCount)
									button1.setEnabled(true);
							}
							else{
								newChar ="";
								currentChar =0;
								String a = "";
								for(int k = 0; k<inputCounter; k++){
									a = a.concat(Integer.toString(input_data[k])).concat(",");
								}
								editText1.setText(a);
								editText1.setSelection(editText1.getText().length());
							}
						}
						else{
							//Toast.makeText(getApplicationContext(), "(3)is a comma valid"+newChar, Toast.LENGTH_LONG).show();
							newChar ="";
							isinValid=true;
							final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
			        				context);
							
			        			// set title
			        			alertDialogBuilder.setTitle("Error: ");
			        			
			        			alertDialogBuilder.setCancelable(false);
			        			alertDialogBuilder.setMessage("Entered Invalid Input: Please enter another number!");					        			        			
			        			alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			        				public void onClick(DialogInterface dialog, int whichButton) {
			        					return;
			        				  }
			        				});
			        				// show it
			        			alertDialogBuilder.show();

			        			
				        		String a = "";
				        		currentChar =0;
								for(int i = 0; i<inputCounter; i++){
									a = a.concat(Integer.toString(input_data[i])).concat(",");
								}
								editText1.setText(a);
								editText1.setSelection(editText1.getText().length());
			        		}
					}
					editText1.setSelection(editText1.getText().length());
				}
				else{
					
					newChar = newChar.concat(Character.toString(currentChar));
					
				}
				

				Log.i("Pankaj", "s = "+currentChar);//("s "+s);
				if(Character.toString(s.charAt(before)).equals(",")){
		        	//Toast.makeText(getApplicationContext(), "is a comma valid"+s, Toast.LENGTH_LONG).show();

					//AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
			 
						// set title
						//alertDialogBuilder.setTitle("Your Title"+s);
				}
				
				 }catch(IndexOutOfBoundsException ioe){
                     System.out.print("Regular!  ");
             }	
			
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}

		});
       
        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	toastMsg.makeText(getApplicationContext(), "New Bubble Sort", toastMsg.LENGTH_LONG).show();
            	editText1.setVisibility(View.VISIBLE);
            	editText2.setVisibility(View.VISIBLE);
            	button1.setVisibility(View.	VISIBLE);
            	button5.setVisibility(View.INVISIBLE);
            	textView1.setVisibility(View.VISIBLE);
            	TextView01.setVisibility(View.VISIBLE);
            	inputCounter = 0;
            	for(int i = 0; i<input_data.length; i++){
        			input_data[i] =-1;	
        		}
            	editText1.setEnabled(true);
            	editText2.setEnabled(false);
            	
            	editText1.setHint("Only letters, digits, and digit seperator comma");
            	if(isConfigchange == true)
            	{
            		isConfigchange = false;
					

	            	if(inputEnd > inputStart && ((inputEnd-inputStart)>=inputMinCount) 
	            			&& (inputMinCount >0) && (inputMaxCount <=100))
	    			{
	                	inputStartRange = inputStart;
	                	inputEndRange = inputEnd;
	                	inputMinElementCount = inputMinCount;
						inputMsxElementCount = inputMaxCount;
	                	
	    			}
	    			else
	    			{
;
	    				final AlertDialog.Builder alertDialogBuilder3 = new AlertDialog.Builder(
	            				context);
	             
	            			// set title
	            			alertDialogBuilder3.setTitle("Error !!!");
	            			alertDialogBuilder3.setMessage("Check your Input Data. Start and End Range should be Valid and Range difference should be atleast 10");
	            			alertDialogBuilder3.setCancelable(false);
	            			alertDialogBuilder3.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	            				public void onClick(DialogInterface dialog, int whichButton) {
	
	            				  // Do something with value!
	            				  }
	            				});
	           
	            				// show it
	            			alertDialogBuilder3.show();
	            			button5.setVisibility(View.INVISIBLE);
	    				
	    			}
            	}
            	textView1.setText("Enter the Number: "+inputStartRange+" to "+inputEndRange);
            	TextView01.setText("Total Number Entered: "+inputCounter + "Remaining Max Entries"+(inputMsxElementCount-inputCounter));
            	editText1.setText("");
            	editText2.setText("");
            	v.invalidate(); 
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	editText1.setEnabled(false);
            	editText2.setEnabled(true);
            	SortasBubble();
            	String stringResult = "";
                for (int i = 0; i < input_data.length; i++){
                	if(input_data[i] >=0){
                		stringResult += input_data[i] + " ";
                	}
                }    
                editText2.setText(stringResult);
                button1.setEnabled(false);
                button2.setEnabled(true);
                button5.setVisibility(View.VISIBLE);
                TextView01.setText("Sorted Output: ");
                v.invalidate(); 
            }
            
        });
        
        button2.setOnClickListener(new View.OnClickListener() {
        	
        	
            @Override
            public void onClick(View v) {
            	newChar = "";
            	inputCounter = 0;
            	editText1.setText("");
            	editText2.setText("");
            	v.invalidate(); 
            	editText1.setEnabled(false);
            	editText2.setEnabled(false);
            	editText1.setHint("Press Start New Bubble Sort Button");
            	toastMsg.makeText(getApplicationContext(), "Ener the Configuration Data!", toastMsg.LENGTH_LONG).show();
            	button5.setVisibility(View.INVISIBLE);
            	final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        				context);
         
        			// set title
        			alertDialogBuilder.setTitle("Bubblesort End Range: ");
         			final EditText input2 = new EditText(MainActivity.this);
         			int maxLength = 3;
         			InputFilter filter = new InputFilter(){
         			@Override
         			public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend ) {
						return dest;
         				}
         		    };
         		   input2.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
        			alertDialogBuilder.setView(input2);
        			alertDialogBuilder.setCancelable(false);
        			input2.setInputType(InputType.TYPE_CLASS_NUMBER);
        			        			
        			alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dialog, int whichButton) {
        					String inVal = input2.getText().toString();
        					if(inVal.isEmpty()){
        						toastMsg.makeText(getApplicationContext(), "No Input", toastMsg.LENGTH_LONG).show();
        						return;
        					}
        					inputEnd = Integer.parseInt(input2.getText().toString());
        					isConfigchange = true;
        				  }
        				});
        			alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        				  public void onClick(DialogInterface dialog, int whichButton) {
        				    // Canceled.
        				  }
        			});
       
        				// show it
        			alertDialogBuilder.show();
        			
        			


                	final AlertDialog.Builder alertDialogBuilder1 = new AlertDialog.Builder(
            				context);
             
            			// set title
            			alertDialogBuilder1.setTitle("Bubblesort Start Range: ");
            			final EditText input1 = new EditText(MainActivity.this);

            			alertDialogBuilder1.setView(input1);

            			alertDialogBuilder1.setCancelable(false);
            			input1.setInputType(InputType.TYPE_CLASS_NUMBER);
            			int maxLength1 = 3;
             			InputFilter filter1 = new InputFilter(){
             			@Override
             			public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend ) {
    						return dest;
             				}
             		    };
             		   input1.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength1)});

            			        			
            			alertDialogBuilder1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            				public void onClick(DialogInterface dialog, int whichButton) {
            					String inVal = input1.getText().toString();
            					if(inVal.isEmpty()){
            						toastMsg.makeText(getApplicationContext(), "No Input", toastMsg.LENGTH_LONG).show();
            						return;
            					}
            					inputStart = Integer.parseInt(input1.getText().toString());
            					isConfigchange = true;
            				  }
            				});
            			alertDialogBuilder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            				  public void onClick(DialogInterface dialog, int whichButton) {
            				    // Canceled.
            				  }
            			});
           
            				// show it
            			alertDialogBuilder1.show();

            	final AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(
        				context);
         
        			// set title
        			alertDialogBuilder2.setTitle("Bubblesort Number of Elements: Max:");
        			final EditText input = new EditText(MainActivity.this);

        			alertDialogBuilder2.setView(input);

        			alertDialogBuilder2.setCancelable(false);
        			input.setInputType(InputType.TYPE_CLASS_NUMBER);
        			        			
        			alertDialogBuilder2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dialog, int whichButton) {
        					String inVal = input.getText().toString();
        					if(inVal.isEmpty()){
        						toastMsg.makeText(getApplicationContext(), "No Input", toastMsg.LENGTH_LONG).show();
        						return;
        					}

        				    inputMaxCount = Integer.parseInt(input.getText().toString());
        					if(inputMaxCount <= 0 && inputMaxCount >100){
        						toastMsg.makeText(getApplicationContext(), "No Input", toastMsg.LENGTH_LONG).show();
        						inputMaxCount =0;
        						return;
        					}
        					isConfigchange = true;

        				  // Do something with value!
        				  }
        				});
        			alertDialogBuilder2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        				  public void onClick(DialogInterface dialog, int whichButton) {
        				    // Canceled.
        				  }
        			});
       
        				// show it
        			alertDialogBuilder2.show();
        			
        			final AlertDialog.Builder alertDialogBuilder3 = new AlertDialog.Builder(
            				context);
             
            			// set title
            			alertDialogBuilder3.setTitle("Bubblesort Number of Elements:Minimum");
            			final EditText input5 = new EditText(MainActivity.this);

            			alertDialogBuilder3.setView(input5);

            			alertDialogBuilder3.setCancelable(false);
            			input5.setInputType(InputType.TYPE_CLASS_NUMBER);
            			        			
            			alertDialogBuilder3.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            				public void onClick(DialogInterface dialog, int whichButton) {
            					String inVal = input5.getText().toString();
            					if(inVal.isEmpty()){
            						toastMsg.makeText(getApplicationContext(), "No Input", toastMsg.LENGTH_LONG).show();
            						return;
            					}

            				    inputMinCount = Integer.parseInt(input5.getText().toString());
            					if(inputMinCount <= 0 && inputMinCount >100){
            						toastMsg.makeText(getApplicationContext(), "No Input", toastMsg.LENGTH_LONG).show();
            						inputMinCount =0;
            						return;
            					}
            					isConfigchange = true;

            				  // Do something with value!
            				  }
            				});
            			alertDialogBuilder3.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            				  public void onClick(DialogInterface dialog, int whichButton) {
            				    // Canceled.
            				  }
            			});
           
            				// show it
            			alertDialogBuilder3.show();

   
            			button5.setVisibility(View.VISIBLE);
            			//toastMsg.makeText(getApplicationContext(), "And then Click Start New Bubble Sort Now!", toastMsg.LENGTH_LONG).show();
            }

        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	editText2.setEnabled(false);
            	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
        				context);
         
        			// set title
        			alertDialogBuilder.setTitle("Help: Ultimate Sorter Help");
        			// set dialog message
        			String str ="";
        			String str1 ="";
        			str +=inputStartRange;
        			str1 +=inputEndRange;
        			
        			alertDialogBuilder
        				.setMessage("Bubble Sorter: Input range "+ str+" - "+ str1+
        						" and Maximum Number of Inputs: 12  seperated by Comma " +
        						" Minimun Number of Inputs: 10")
        				.setCancelable(true)
        				.setPositiveButton("OK",new DialogInterface.OnClickListener() {
        					public void onClick(DialogInterface dialog,int id) {
        						// if this button is clicked, close
        						// current activity
        						dialog.cancel();
        					}
        				  });
         
        				// create alert dialog
        				AlertDialog alertDialog = alertDialogBuilder.create();
         
        				// show it
        				alertDialog.show();
        			}
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	finish();
                System.exit(0);
            }
        });
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
    void SortasBubble() {
    	int lower;
    	String Sortprocess ="";
    	for (int i = 0; i < input_data.length - 1; i++){
    		if(input_data[i] >=0){
    		lower = i;
    		for (int  j = i + 1; j < input_data.length; j++){	
	    			if (input_data[j] < input_data[lower]){
	    				lower = j;
	    			}	
	    		}
    		if (i != lower){ 
    			int tmp = input_data[i];
    			input_data[i] = input_data[lower];
    			input_data[lower] = tmp;
    		}
    		for (int k = 0; k < input_data.length; k++){
    			if(input_data[k] >=0){
    				Sortprocess += input_data[k] + " ";
    				//toastMsg.makeText(getApplicationContext(), Sortprocess, toastMsg.LENGTH_LONG).show();
    			}
	        	
	        } 
			Sortprocess="";
    		}
    	}
    }
}
